package com.masterclient.app;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.activity.FCActivitySupportProtocol;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselibrary.utils.UtilCollection;
import com.eoner.baselibrary.widget.PermissionDialog;
import com.eoner.common.BuildConfig;
import com.eoner.common.config.Config;
import com.eoner.commonbean.UrlParam;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.servertimer.ServerTimerManager;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.managerlibrary.version.VersionManager;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.eoner.middlelib.eventbus.event.HomeRefreshEvent;
import com.eoner.middlelib.eventbus.event.LoginSuccessEvent;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.base.FrozenDialog;
import com.masterclient.app.businessmodule.homemodule.fragment.ExhibitsClassifyFragment;
import com.masterclient.app.businessmodule.homemodule.fragment.HomeFragment;
import com.masterclient.app.businessmodule.homemodule.fragment.MineFragment;
import com.masterclient.app.businessmodule.usermodule.login.index.QuickLoginActivity;
import com.masterclient.app.businessmodule.vipmodule.fragment.VipCenterFragment;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.modules.bridge.BridgeFragment;
import com.masterclient.app.modules.cart.ShopCartFragment;
import com.masterclient.app.modules.category.CategoryFragment;
import com.masterclient.app.modules.main.MainContract;
import com.masterclient.app.modules.main.MainPresenter;
import com.masterclient.app.utils.CommonUtil;
import com.google.gson.Gson;
import com.sobot.chat.utils.ZhiChiConstant;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;

@Route(path = AroutePath.MAIN_ACTIVITY)
public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View, View.OnClickListener, FCActivitySupportProtocol {

    @BindView(R.id.fl_container)
    FrameLayout flContainer;

    @BindView(R.id.view_recommend)
    View viewRecommend;
    @BindView(R.id.view_vip)
    View viewVip;
    @BindView(R.id.view_person)
    View viewPerson;

    ///image
    @BindView(R.id.iv_recommend)
    ImageView ivRecommend;
    @BindView(R.id.iv_vip)
    ImageView ivVip;

    @BindView(R.id.iv_person)
    ImageView ivPerson;

    ///text
    @BindView(R.id.tv_recommend)
    TextView tvRecommend;
    @BindView(R.id.tv_vip)
    TextView tvVip;
    @BindView(R.id.tv_person)
    TextView tvPerson;


    @BindView(R.id.update_environment)
    TextView updateEnvironment;

    @Autowired(name = "code")
    String code;
    @Autowired(name = "position")
    String position;

    public HomeFragment homePageFragment;
    public BridgeFragment vipFragment;
    public ExhibitsClassifyFragment exhibitsClassifyFragment;
    public MineFragment personalFragment;

    private String[] tags = {HomeFragment.TAG, CategoryFragment.TAG, VipCenterFragment.TAG, ShopCartFragment.TAG, MineFragment.TAG};
    private FragmentManager fm;
    public Fragment currentFragment;
    private RxBus rxBus;
    private Gson gson;
    private long exitTime = 0;
    private int beforePosition = 0;
    public int curPosition = -1;

    private RxPermissions rxPermissions;

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int noReadNum = intent.getIntExtra("noReadCount", 0);
            Config.UNREAD = noReadNum;
            rxBus.post(Config.MSG_UNREAD, "1");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBusManager.register(this);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);

        if (BuildConfig.ISENV) {
            updateEnvironment.setVisibility(View.VISIBLE);
            updateEnvironment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ARouter.getInstance().build(AroutePath.PERSONAL_UPDATE_ENVIRONMENT).navigation();
                }
            });
        } else {
            updateEnvironment.setVisibility(View.GONE);
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ZhiChiConstant.sobot_unreadCountBrocast);
        registerReceiver(receiver, filter);

        fm = getSupportFragmentManager();
        rxBus = RxBus.$();
        onInit(savedInstanceState);

        Intent intent = getIntent();
        if (intent != null) {
            String data = intent.getDataString();
            if (data != null) {
                Uri uri = Uri.parse(data);
                String json_info = uri.getQueryParameter("json_info");
                Gson gson = new Gson();
                UrlParam param = gson.fromJson(json_info, UrlParam.class);

                if (param != null) {
                    if ("product".equals(param.getTarget())) {
                        ARouter.getInstance().build(AroutePath.COMMODITY_DETAIL_ACTIVITY)
                                .withString("id", param.getTarget_id())
                                .navigation();
                    } else if ("store".equals(param.getTarget())) {
                        ARouter.getInstance().build(AroutePath.STORE_ACTIVITY).withString("store_id", param.getTarget_id()).navigation();
                    }
                }
            }

            Map<String, String> map = (Map<String, String>) intent.getSerializableExtra("extra");
            if (map != null) {
                switch (map.get("goto_page")) {
                    case "index":
                        break;
                    case "subject":
                        startActivitry(BridgeActivity.class, new String[][]{{"url", map.get("page_id")}});
                        break;
                    case "product":
                        ARouter.getInstance().build(AroutePath.COMMODITY_DETAIL_ACTIVITY)
                                .withString("id", map.get("page_id"))
                                .navigation();
                        break;
                    case "seller":
                        ARouter.getInstance().build(AroutePath.STORE_ACTIVITY).withString("store_id", map.get("page_id")).navigation();
                        break;
                }
            }

            String target = intent.getStringExtra("target");
            String target_id = intent.getStringExtra("target_id");
            if (!TextUtils.isEmpty(target)) {// && !TextUtils.isEmpty(target_id)
                CommonUtil.goAnyWhere(mContext, target, target_id, "", "", "");
            }

            if ("2".equals(intent.getStringExtra("code")) || "1101".equals(intent.getStringExtra("code"))) {
                //TODO:退出IM
                startActivitry(QuickLoginActivity.class, new String[][]{{"intentSource", "首页"}});
            } else {
                if (code != null && code.equals("1101")) {
                    //TODO:退出IM
                    startActivitry(QuickLoginActivity.class, new String[][]{{"intentSource", "首页"}});
                }
            }
        }
        isActive = false;

        rxBus.OnEvent(rxBus.register(Config.GO_FIRST_PAGE), new Consumer<Object>() {
            @Override
            public void accept(@NonNull Object o) throws Exception {
                if (curPosition != 0) {
                    setRadioChecked(0);
                }
            }
        });

        isActive = false;


        //进入首页 消息通知弹出
        if (!UtilCollection.get_notification_flag(MainActivity.this)
                && !UtilCollection.isNotificationEnabled(this)) {
            display_notification_tip_dialog();
            UtilCollection.save_notification_flag(this, true);
        }

    }

    @Override
    public int currentSelPosition() {
        return this.curPosition;
    }

    private void display_notification_tip_dialog() {
        ConfirmDialog confirmDialog = new ConfirmDialog(mContext, "开启通知,重要消息不错过", "取消", "确定");
        confirmDialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
            @Override
            public void cancel() {
                confirmDialog.dismiss();
            }

            @Override
            public void confirm() {
                confirmDialog.dismiss();
                UtilCollection.requestNotify(MainActivity.this);
            }
        });
        confirmDialog.show();
    }

    /**
     * 登录成功刷新
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginSuccessEvent(LoginSuccessEvent event) {
        VersionManager.getInstance().setActivity(this);
        VersionManager.getInstance().requestCheckVersionUpdate(false);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                String customerType = SystemConfigStorage.getInstance().getCustomerType();
                if ("1".equals(customerType)) {
                    tvVip.setText("我要参展");
                } else if ("2".equals(customerType)) {
                    tvVip.setText("志愿服务");
                } else if ("3".equals(customerType)) {
                    tvVip.setText("展务会务");
                } else {
                    tvVip.setText("展品鉴赏");
                }
                setRadioChecked(0);
            }
        },2000);
        setRadioChecked(0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        VersionManager.getInstance().setActivity(this);
        VersionManager.getInstance().requestCheckVersionUpdate(false);

        String customerType = SystemConfigStorage.getInstance().getCustomerType();
        if ("1".equals(customerType)) {
            tvVip.setText("我要参展");
        } else if ("2".equals(customerType)) {
            tvVip.setText("志愿服务");
        } else if ("3".equals(customerType)) {
            tvVip.setText("展务会务");
        } else {
            tvVip.setText("展品鉴赏");
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Map<String, String> map = (Map<String, String>) intent.getSerializableExtra("extra");
        if (map != null) {
            switch (map.get("goto_page")) {
                case "index":
                    break;
                case "subject":
                    startActivitry(BridgeActivity.class, new String[][]{{"url", map.get("page_id")}});
                    break;
                case "product":
                    ARouter.getInstance().build(AroutePath.COMMODITY_DETAIL_ACTIVITY)
                            .withString("id", map.get("page_id"))
                            .navigation();
                    break;
                case "seller":
                    ARouter.getInstance().build(AroutePath.STORE_ACTIVITY).withString("store_id", map.get("page_id")).navigation();
                    break;
            }
        }

        if (intent.getExtras() != null) {
            String position = intent.getExtras().getString("position");
            if (position != null) {
                switchRadioGroup(TextUtils.isEmpty(position) ? 0 : Integer.parseInt(position));
            }
        }
        super.onNewIntent(intent);
    }

    private void onInit(Bundle savedInstanceState) {
        //初始化用户信息
        gson = new Gson();
        if (savedInstanceState != null) {
            homePageFragment = (HomeFragment) fm.findFragmentByTag(HomeFragment.TAG);
            vipFragment = (BridgeFragment) fm.findFragmentByTag(VipCenterFragment.TAG);
            personalFragment = (MineFragment) fm.findFragmentByTag(MineFragment.TAG);
            switchRadioGroup(savedInstanceState.getInt("curPosition"));
        } else {
            if (homePageFragment == null) {
                homePageFragment = HomeFragment.newInstance();
                currentFragment = homePageFragment;
                getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.fl_container, homePageFragment, HomeFragment.TAG)
                        .commitAllowingStateLoss();
                setRadioChecked(0);
            }
        }

        rxPermissions = new RxPermissions(this);
        boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (!hasPermissions) {
            new PermissionDialog(this, "开启存储权限", "展示商品信息和图片需要使用存储权限，请在下一个页面点击“允许”",
                    R.mipmap.icon_permission_storage, this::requestPermissions).show();
        }

        viewRecommend.setOnClickListener(this);
        viewVip.setOnClickListener(this);
        viewPerson.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (homePageFragment == null) {
            homePageFragment = HomeFragment.newInstance();
        }
        switchTab(id);
    }

    private void requestPermissions() {
        rxPermissions
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> { // will emit 2 Permission objects
                    if (permission.granted) {
                        // `permission.name` is granted !
                        //mLocationClient.start();
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // Denied permission without ask never again
                    } else {
                        // Denied permission with ask never again
                        // Need to go to the settings
                    }
                });
    }

    /**
     * fragment 切换
     *
     * @param from
     * @param to
     */
    public void switchContent(Fragment from, Fragment to, int position) {
        if (currentFragment != to) {
            currentFragment = to;
            FragmentTransaction transaction = fm.beginTransaction();
            if (from != null && to != null && tags != null) {
                if (!to.isAdded()) {
                    // 先判断是否被add过
                    transaction.hide(from)
                            .add(R.id.fl_container, to, tags[position]).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到Activity中
                } else {
                    transaction.hide(from).show(to).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
                }
            }
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("curPosition", beforePosition);
        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            showToast("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            ServerTimerManager.getInstance().stopTimerTask();
            finish();
            System.exit(0);
        }
    }

    public void setRadioChecked(int position) {
        int id = 0;
        if (position == 0) {
            id = R.id.view_recommend;
        } else if (position == 1) {
            id = R.id.view_vip;
        } else if (position == 2) {
            id = R.id.view_person;
        }
        switchTab(id);
    }

    public void switchRadioGroup(int position) {
        switch (position) {
            case 0:
                viewRecommend.postDelayed(() -> switchTab(R.id.view_recommend), 200);
                break;
            case 1:
                viewVip.postDelayed(() -> switchTab(R.id.view_vip), 200);
                break;
            case 2:
                viewPerson.postDelayed(() -> switchTab(R.id.view_person), 200);
                break;
        }
    }

    private void switchTab(int id) {
        String customerType = SystemConfigStorage.getInstance().getCustomerType();
        if (homePageFragment == null) {
            homePageFragment = HomeFragment.newInstance();
        }
        if (id == R.id.view_recommend) {
            if (curPosition == 0) {
                return;
            }
            curPosition = 0;
            beforePosition = 0;
            switchContent(currentFragment, homePageFragment, 0);
        } else if (id == R.id.view_vip) {
            if (curPosition == 1) {
                String centerUrl = "";
                if ("1".equals(customerType) || "2".equals(customerType) || "3".equals(customerType)) {
                    if ("1".equals(customerType)) {
                        centerUrl = SystemConfigStorage.getInstance().getApplyUrl();
                    } else if ("2".equals(customerType)) {
                        centerUrl = SystemConfigStorage.getInstance().getVolunteerUrl();
                    } else if ("3".equals(customerType)) {
                        centerUrl = SystemConfigStorage.getInstance().getWorkerUrl();
                    }
                    if (vipFragment == null) {
                        vipFragment = BridgeFragment.newInstance(centerUrl);
                    } else {
                        vipFragment.refreshUrl(centerUrl);
                    }
                    vipFragment.reLoad();
                } else {
                    if (exhibitsClassifyFragment == null) {
                        exhibitsClassifyFragment = ExhibitsClassifyFragment.getInstance();
                    }
                }
                return;
            }
            curPosition = 1;
            if ("2".equals(Config.FROZEN)) {
                FrozenDialog.showFrozen(mContext);
                switchRadioGroup(beforePosition);
                return;
            }
            if (!UserDataManager.getInstance().isSystemLogin() &&
                    ("1".equals(customerType) || "2".equals(customerType) || "3".equals(customerType))) {
                startActivitry(QuickLoginActivity.class, new String[][]{{"intentSource", "首页"}});
                switchRadioGroup(beforePosition);
            } else {
                String centerUrl = "";
                if ("1".equals(customerType) || "2".equals(customerType) || "3".equals(customerType)) {
                    if ("1".equals(SystemConfigStorage.getInstance().getCustomerType())) {
                        centerUrl = SystemConfigStorage.getInstance().getApplyUrl();
                    } else if ("2".equals(SystemConfigStorage.getInstance().getCustomerType())) {
                        centerUrl = SystemConfigStorage.getInstance().getVolunteerUrl();
                    } else if ("3".equals(SystemConfigStorage.getInstance().getCustomerType())) {
                        centerUrl = SystemConfigStorage.getInstance().getWorkerUrl();
                    }
                    if (vipFragment == null) {
                        vipFragment = BridgeFragment.newInstance(centerUrl);
                    } else {
                        vipFragment.refreshUrl(centerUrl);
                    }
                    vipFragment.reLoad();
                    beforePosition = 1;
                    switchContent(currentFragment, vipFragment, 1);
                } else {
                    if (exhibitsClassifyFragment == null) {
                        exhibitsClassifyFragment = ExhibitsClassifyFragment.getInstance();
                    }
                    beforePosition = 1;
                    switchContent(currentFragment, exhibitsClassifyFragment, 1);
                }
            }
        } else if (id == R.id.view_person) {
            if (curPosition == 2) {
                return;
            }
            curPosition = 2;

            if ("2".equals(Config.FROZEN)) {
                FrozenDialog.showFrozen(mContext);
                switchRadioGroup(beforePosition);
                return;
            }
            if (!UserDataManager.getInstance().isSystemLogin()) {
                startActivitry(QuickLoginActivity.class, new String[][]{{"intentSource", "首页"}});
                switchRadioGroup(beforePosition);
            } else {
                if (personalFragment == null) {
                    personalFragment = MineFragment.newInstance();
                }
                beforePosition = 2;
                switchContent(currentFragment, personalFragment, 2);
            }
        }
        switchTabStatus(curPosition);
    }


    private void switchTabStatus(int position) {
        String customerType = SystemConfigStorage.getInstance().getCustomerType();
        switch (position) {
            case 0:
                if (tvRecommend.getCurrentTextColor() == Color.parseColor("#333333")) {
                    return;
                }
                tvRecommend.setTextColor(Color.parseColor("#333333"));
                tvVip.setTextColor(Color.parseColor("#999999"));
                tvPerson.setTextColor(Color.parseColor("#999999"));

                if ("1".equals(customerType)) {
                    ivVip.setImageResource(R.mipmap.tab_icon_vip_unpressed);
                } else if ("2".equals(customerType)) {
                    ivVip.setImageResource(R.mipmap.tab_icon_volunteer_unpressed);
                } else if ("3".equals(customerType)) {
                    ivVip.setImageResource(R.mipmap.tab_icon_vip_unpressed);
                } else {
                    ivVip.setImageResource(R.mipmap.tab_icon_exhibits_unpressed);
                }
                ivRecommend.setImageResource(R.mipmap.home_page_sel);
                ivPerson.setImageResource(R.mipmap.home_personal_default);
                break;
            case 1:
                tvRecommend.setTextColor(Color.parseColor("#999999"));
                tvVip.setTextColor(Color.parseColor("#333333"));
                tvPerson.setTextColor(Color.parseColor("#999999"));

                ivRecommend.setImageResource(R.mipmap.home_page_default);
                ivPerson.setImageResource(R.mipmap.home_personal_default);
                if ("1".equals(customerType)) {
                    ivVip.setImageResource(R.mipmap.tab_icon_vip_pressed);
                } else if ("2".equals(customerType)) {
                    ivVip.setImageResource(R.mipmap.tab_icon_volunteer_pressed);
                } else if ("3".equals(customerType)) {
                    ivVip.setImageResource(R.mipmap.tab_icon_vip_pressed);
                } else {
                    ivVip.setImageResource(R.mipmap.tab_icon_exhibits_pressed);
                }
                break;
            case 2:
                if (tvPerson.getCurrentTextColor() == Color.parseColor("#333333")) {
                    return;
                }
                tvRecommend.setTextColor(Color.parseColor("#999999"));
                tvVip.setTextColor(Color.parseColor("#999999"));
                tvPerson.setTextColor(Color.parseColor("#333333"));

                if ("1".equals(customerType)) {
                    ivVip.setImageResource(R.mipmap.tab_icon_vip_unpressed);
                } else if ("2".equals(customerType)) {
                    ivVip.setImageResource(R.mipmap.tab_icon_volunteer_unpressed);
                } else if ("3".equals(customerType)) {
                    ivVip.setImageResource(R.mipmap.tab_icon_vip_unpressed);
                } else {
                    ivVip.setImageResource(R.mipmap.tab_icon_exhibits_unpressed);
                }
                ivRecommend.setImageResource(R.mipmap.home_page_default);
                ivPerson.setImageResource(R.mipmap.home_personal_selected);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //处理二维码扫描结果
        if (requestCode == HomeFragment.REQUEST_CODE && resultCode == 3) {
            String result = data.getStringExtra("result");
            if (vipFragment != null) {
                vipFragment.scanResult(result);
            }
        }
    }

    /**
     * 首页刷新 (这里在登录、退出登录的时候都会触发)
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void homeDataRefresh(HomeRefreshEvent event) {
    }

    @Override
    protected void onDestroy() {
        if (rxBus != null) {
            rxBus.unregister(Config.VIDEO_SELECT);
            rxBus.unregister(Config.GO_FIRST_PAGE);
        }
        super.onDestroy();
        EventBusManager.unRegister(this);
        unregisterReceiver(receiver);
    }
}
